package com.jdd.modules.system.util;

import com.jdd.common.constant.HttpConstant;
import com.jdd.common.constant.StringSymbol;
import com.jdd.common.util.oConvertUtils;
import com.jdd.modules.system.entity.SysPermission;

import java.util.List;

/**
 * @Author: scott
 * @Date: 2019-04-03
 */
public class PermissionDataUtil {


	private static final String VIEWS = "views/";
	private static final String SRC_VIEWS = "src/views/";
	private static final String POINT_VUE = ".vue";

	/**
	 * 智能处理错误数据，简化用户失误操作
	 *
	 * @param permission
	 */
	public static SysPermission intelligentProcessData(SysPermission permission) {
		if (permission == null) {
			return null;
		}

		// 组件
		if (oConvertUtils.isNotEmpty(permission.getComponent())) {
			String component = permission.getComponent();
			if (component.startsWith(StringSymbol.BACKSLASH)) {
				component = component.substring(1);
			}
			if (component.startsWith(VIEWS)) {
				component = component.replaceFirst(VIEWS, "");
			}
			if (component.startsWith(SRC_VIEWS)) {
				component = component.replaceFirst(SRC_VIEWS, "");
			}
			if (component.endsWith(POINT_VUE)) {
				component = component.replace(POINT_VUE, "");
			}
			permission.setComponent(component);
		}

		// 请求URL
		if (oConvertUtils.isNotEmpty(permission.getUrl())) {
			String url = permission.getUrl();
			if (url.endsWith(POINT_VUE)) {
				url = url.replace(POINT_VUE, "");
			}
			if (!url.startsWith(HttpConstant.HTTP)
					&& !url.startsWith(StringSymbol.BACKSLASH)
					&&!url.trim().startsWith(StringSymbol.DOUBLE_LEFT_CURLY_BRACES)) {
				url = "/" + url;
			}
			permission.setUrl(url);
		}

		// 一级菜单默认组件
		if (0 == permission.getMenuType() && oConvertUtils.isEmpty(permission.getComponent())) {
			// 一级菜单默认组件
			permission.setComponent("layouts/RouteView");
		}
		return permission;
	}

	/**
	 * 如果没有index页面 需要new 一个放到list中
	 * @param metaList
	 */
	public static void addIndexPage(List<SysPermission> metaList) {
		boolean hasIndexMenu = false;
		for (SysPermission sysPermission : metaList) {
			if("首页".equals(sysPermission.getName())) {
				hasIndexMenu = true;
				break;
			}
		}
		if(!hasIndexMenu) {
			metaList.add(0,new SysPermission(true));
		}
	}

}
